package per.turtle.gateway.filter;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import per.turtle.common.core.web.entity.Captcha;
import per.turtle.common.core.web.entity.CommonResult;
import per.turtle.gateway.service.ValidateCodeService;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 验证码过滤器
 *
 * @author turtle
 */
@Component
@RequiredArgsConstructor
public class ValidateCodeFilter extends AbstractGatewayFilterFactory<Object> {

    /**
     * 校验验证码的访问路径集合
     */
    private final static String[] VALIDATE_URL = {"/auth/login"};

    private final static String CAPTCHA = "captcha";

    private final ValidateCodeService validateCodeService;

    @Value("${ignore.validateCode:true}")
    private Boolean validateCode;

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();

            // 登录请求，且开启校验时处理
            if (validateCode && Arrays.stream(VALIDATE_URL).anyMatch(url -> url.equals(request.getURI().getPath()))) {
                try {
                    String rspStr = resolveBodyFromRequest(request);
                    JSONObject obj = JSONUtil.parseObj(rspStr);
                    Captcha captcha = obj.get(CAPTCHA, Captcha.class);
                    validateCodeService.checkCaptcha(captcha.getCode(), captcha.getUuid());
                } catch (Exception e) {
                    ServerHttpResponse response = exchange.getResponse();
                    response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
                    return exchange.getResponse()
                                   .writeWith(Mono.just(response.bufferFactory().wrap(JSONUtil.toJsonStr(CommonResult.error(e.getMessage())).getBytes())));
                }
            }
            return chain.filter(exchange);
        };
    }

    private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest) {
        // 获取请求体
        Flux<DataBuffer> body = serverHttpRequest.getBody();
        AtomicReference<String> bodyRef = new AtomicReference<>();
        body.subscribe(buffer -> {
            CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.asByteBuffer());
            DataBufferUtils.release(buffer);
            bodyRef.set(charBuffer.toString());
        });
        return bodyRef.get();
    }

}
